﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using iTool.Cloud.Database.iToolService;
using iTool.Cloud.Database.KeyGeneratorProvider.Contract;
using iTool.Cloud.Database.Options;
using iTool.Cloud.Database.MaxVersionPlacementStrategyFixedProvider;
using iTool.Cloud.Database.SqlStructureProvider.Options;

using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Options;

using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.Runtime;

namespace iTool.Cloud.Database.ServiceProvider.Implementation
{
    /// <summary>
    /// 在最大Version 上激活
    /// </summary>
    [Reentrant]
    [MaxVersionPlacementStrategy]
    public class TableSyncLoggerService : iToolServiceDataBase, iTableSyncLoggerService
    {
        public TableSyncLoggerService(KeyGeneratorOptions options, IOptions<ClusterOptions> clusterOptions, ISiloStatusOracle siloStatusOracle) : base(options, clusterOptions, siloStatusOracle)
        {
        }

        public async Task<List<BLoggerOptions>?> GetSyncSqlScriptAsync(long lastversion)
        {
            using (var connection = await this.GetDBVersionConnectionAsync())
            {
                using (var command = new SqliteCommand(String.Intern($"select rowid,action,keys,sql,extend,tranId from {this.TableName} where rowid > $maxrowid limit 1000"), connection))
                {
                    command.Parameters.AddWithValue("$maxrowid", lastversion);
                    var reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        return PropertyUtils<BLoggerOptions>.ConvertDataReaderToEntity(reader);
                    }
                }
            }

            return null;
        }

        public Task<(List<string> locations, List<string> fields)> GetAllIndexFieldAsync()
        {
            return this.GetAllIndexFieldsAsync();
        }

        public Task<IEnumerable<FieldOptions>> GetTableAllFieldAsync()
        {
            return GetSqlStructureProviderByTableName(this.TableName).GetAllFieldsAsync();
        }
    }
}
